/*
 * Module name : ProductFilterForm
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import {
    serializeForm
} from '../../../tools.js';
import InputWidget from '../../../widgets/InputWidget.js';
import SelectWidget from '../../../widgets/SelectWidget.js';

const template = require('./templates/ProductFilterForm.mustache');

const DeleteFiltersView = Mn.View.extend({
    template: require('./templates/DeleteFiltersView.mustache'),
});

const ProductFilterForm = Mn.View.extend({
    template: template,
    childView: DeleteFiltersView,
    regions: {
        'delete_filters': '#delete_filters',
        type_: '.field-type_',
        'name': '.field-name',
        'description': '.field-description',
        'category_id': '.field-category-id',
        'ref': '.field-ref',
        'supplier_id': '.field-supplier-id',
        'supplier_ref': '.field-supplier-ref',
        'mode': '.field-mode',
    },
    ui: {
        submit_button: 'button[type=submit]',
        form: 'form',
        delete: ".handle_delete_filters"
    },
    events: {
        'click @ui.submit_button': 'onSubmitClicked',
        'click @ui.delete': "onDeleteFilters"
    },
    initialize() {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.model = this.getOption('model');
        this.categories = this.facade.request(
            'get:collection',
            'categories'
        );
        this.listenTo(this.categories, 'add', this.render);
        this.listenTo(this.categories, 'sync', this.render);
        this.listenTo(this.categories, 'remove', this.render);
    },
    onRender() {
        let product_types = this.config.request('get:options', "product_types");
        console.log(product_types);
        this.showChildView(
            'type_',
            new SelectWidget({
                field_name: 'type_',
                label: 'Type de produit',
                options: product_types,
                id_key: 'value',
                label_key: 'label',
                placeholder: "Choisir un type de produit",
                value: this.model.get('type_'),
            })
        );

        this.showChildView(
            'name',
            new InputWidget({
                field_name: 'search',
                placeholder: 'Nom',
                label: 'Nom interne',
                dataList: this.config.request('get:options', 'product_labels'),
                value: this.model.get('search'),
            })
        );

        this.showChildView(
            'description',
            new InputWidget({
                field_name: 'description',
                placeholder: 'Description',
                label: 'Description et notes',
                dataList: this.config.request('get:options', 'product_descriptions'),
                value: this.model.get('description'),
            })
        );

        this.showChildView(
            'supplier_ref',
            new InputWidget({
                field_name: 'supplier_ref',
                placeholder: 'Référence fournisseur',
                label: 'Référence fournisseur',
                dataList: this.config.request('get:options', 'product_suppliers_refs'),
                value: this.model.get('supplier_ref'),
            })
        );

        let categories = this.categories.toJSON();
        if (categories.length > 0) {
            this.showChildView(
                'category_id',
                new SelectWidget({
                    field_name: 'category_id',
                    label: 'Catégorie',
                    options: categories,
                    id_key: 'id',
                    label_key: 'title',
                    placeholder: 'Choisir une catégorie',
                    value: this.model.get('category_id'),
                })
            );
        }
        this.showChildView(
            'ref',
            new InputWidget({
                field_name: 'ref',
                placeholder: 'Référence',
                label: 'Référence',
                dataList: this.config.request('get:options', 'references'),
                value: this.model.get('ref'),
            })
        );
        let suppliers = this.config.request('get:options', 'suppliers');
        if (suppliers.length > 0) {
            this.showChildView(
                'supplier_id',
                new SelectWidget({
                    field_name: 'supplier_id',
                    label: 'Fournisseur',
                    options: suppliers,
                    id_key: 'id',
                    label_key: 'label',
                    placeholder: 'Choisir un fournisseur',
                    value: this.model.get('supplier_id'),
                })
            );
        }
        const modes = this.config.request('get:options', 'modes');
        if (modes.length > 1) {
            this.showChildView('mode', new SelectWidget({
                field_name: 'mode',
                label: "Mode de saisie",
                options: [{
                    value: 'ht',
                    label: "HT"
                }, {
                    value: "ttc",
                    label: "TTC"
                }, {
                    value: 'supplier_ht',
                    label: "Coût d'achat"
                }],
                id_key: "value",
                label_key: "label",
                placeholder: "Choisir un mode de saisie",
                value: this.model.get('mode')
            }))
        }
    },
    templateContext() {
        return {
            productReferences: this.config.request('get:options', 'references'),

        };
    },
    toggleDeleteFilters(show) {
        if (show) {
            this.showChildView(
                'delete_filters',
                new DeleteFiltersView({
                    collection: this.collection
                })
            );
        } else {
            this.getChildView('delete_filters') &&
                this.getChildView('delete_filters').destroy();
        }
    },
    resetForm() {
        this.ui.form[0].reset();
        this.ui.form.find('select').prop("selectedIndex", 0);
    },
    getFiltersValues() {
        let data = serializeForm(this.ui.form);
        const empty = Object.values(data).some(val => val !== '');
        this.toggleDeleteFilters(empty);
        this.model.set(data);
        return data;
    },
    onDeleteFilters(event) {
        this.resetForm();
        this.toggleDeleteFilters(false);
        const data = this.getFiltersValues();
        this.triggerMethod('list:filter', this, data);
    },
    onSubmitClicked(event) {
        event.preventDefault();
        const data = this.getFiltersValues();
        this.triggerMethod('filter:submit', this, data);
    }
});
export default ProductFilterForm